import { genKey, joinPath } from "./tools"
import { ExtendedRouteRecordRaw } from "./types"

export const updateRouteMetaInfo = (routes: ExtendedRouteRecordRaw[]) => {
  ;(function eachFn (routes, parentTitle) {
    routes.forEach(r => {
      if (!r.name) {
        r.name = `generated_name_${genKey()}`
      }

      const metaKey = genKey() + ''
      if (r.meta) {
        r.meta.key = metaKey
      } else {
        r.meta = { key: metaKey }
      }

      r.meta.fullTitle = [parentTitle, r.meta.subTitle || r.meta.title]
        .filter(_ => _)
        .join('/')

      r.children && eachFn(r.children, r.meta.fullTitle)
    })
  })(routes)

  return routes
}

export const toFlatRoutes = (subRoutes: ExtendedRouteRecordRaw[], parentPath?: string): ExtendedRouteRecordRaw[] => {
  const sep = '/'
  
  return subRoutes.reduce((t, _) => {
    const path = _.path.startsWith(sep) || !parentPath
      ? _.path
      : joinPath(parentPath, _.path)
    
    return t.concat(
      _.children ? toFlatRoutes(_.children, path) : { ..._, path }
    )
  }, [])
}

export const getRouteTitle = (route: ExtendedRouteRecordRaw, rawRoutes: ExtendedRouteRecordRaw[]) => {
  const toFlat = (routes: ExtendedRouteRecordRaw[]): ExtendedRouteRecordRaw[] => {
    return routes.reduce((t, r) => {
      return [
        ...t,
        r,
        ...(r.children ? toFlat(r.children) : [])
      ]
    }, [])
  }

  const getParentTitle = (flatedRoutes: ExtendedRouteRecordRaw[], subRoute = route) => {
    const parentRoute = flatedRoutes.find(r => {
      return r.children && r.children.includes(subRoute)
    })
    if (parentRoute) {
      const { title } = parentRoute.meta
      if (title) {
        return title
      } else {
        return getParentTitle(flatedRoutes, parentRoute)
      }
    }
  }

  return route.meta.title || getParentTitle(toFlat(rawRoutes))
}
